package com.pdstudio.http;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pdstudio.app.Application;
import com.pdstudio.util.ConvertUtil;
import com.pdstudio.util.NetUtil;
import com.pdstudio.util.SharePreferenceUtil;

/**
 * 所有获取服务端数据的接口
 * */
public abstract class HttpMethodBase {

	private Context context;
	private Gson mGson;
	private static String BASEURI = "http://222.242.199.5:3888/weatherapp/";
	private static String FOMARTSTRING = "{0}/{1}?appkeys={2}&";
	public final String HTTPSUCCESS = "1";

	private Application mApplication;
	private SharePreferenceUtil mSpUtil;

	public HttpMethodBase(Context context) {

		mApplication = Application.getInstance();
		mSpUtil = mApplication.getSharePreferenceUtil();

		this.context = context;
		/*
		 * 不转换没有 @Expose 注解的字段
		 */
		mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
				.create();
	}

	/**
	 * 请求服务器，获取返回数据
	 * */
	public String connGetServerForResult(String url) {
		String strResult = "";
		if (NetUtil.getNetworkState(context) != NetUtil.NETWORN_NONE) {
			try {
				HttpGet httpRequest = new HttpGet(url);
				// HttpClient对象
				HttpClient httpClient = new DefaultHttpClient();
				// 获得HttpResponse对象
				HttpResponse httpResponse = httpClient.execute(httpRequest);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					// 取得返回的数据
					strResult = EntityUtils.toString(httpResponse.getEntity());
					mSpUtil.setWeatherCache(url, strResult);
				} else {// 网络错误从缓存拿数据
					try {
						strResult = mSpUtil.getWeatherCache(url);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {// 无网络存缓存拿数据
			try {
				strResult = mSpUtil.getWeatherCache(url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return strResult; // 返回结果
	}

	public String Get(String url) {
		return connGetServerForResult(url);
	}

	public String Post(String url, List<NameValuePair> params) {
		return connPostServerForResult(url, params);
	}

	/**
	 * post方法获取服务器内容
	 * */
	public String connPostServerForResult(String url, List<NameValuePair> params) {
		String result = "";
		if (NetUtil.getNetworkState(context) != NetUtil.NETWORN_NONE) {
			try {
				HttpPost hp = new HttpPost(url);
				// 设置字符集
				// HttpEntity entity = new UrlEncodedFormEntity(params,
				// HTTP.UTF_8);
				// 设置参数实体
				// hp.setEntity(entity);
				// 获取HttpClient对象
				HttpClient httpClient = new DefaultHttpClient();
				// 连接超时
				httpClient.getParams().setParameter(
						CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
				// 请求超时
				httpClient.getParams().setParameter(
						CoreConnectionPNames.SO_TIMEOUT, 30000);

				// 获取HttpResponse实例
				HttpResponse httpResp = httpClient.execute(hp);
				// 判断是够请求成功
				if (httpResp.getStatusLine().getStatusCode() == 200) {
					// 获取返回的数据
					result = EntityUtils
							.toString(httpResp.getEntity(), "UTF-8");
					mSpUtil.setWeatherCache(url, result);
					// Log.i("HttpPost", "HttpPost方式请求成功，返回数据如下：");
					// Log.i("result", result);
				} else {
					// Log.i("HttpPost", "HttpPost方式请求失败");
					try {
						result = mSpUtil.getWeatherCache(url);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				result = mSpUtil.getWeatherCache(url);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 从文件中获取信息
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getInfoFromFile(String fileName) {
		String result = "";
		try {
			FileInputStream fis = new FileInputStream(fileName);
			byte[] buffer = new byte[fis.available()];// 本地文件可以实例化buffer，网络文件不可行
			fis.read(buffer);
			result = new String(buffer);
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String buildUri(String funcName, String methodName,
			String appkey, Map<String, String> parameters) {
		String uri = BASEURI
				+ MessageFormat.format(FOMARTSTRING, funcName, methodName,
						appkey);
		if (parameters == null) {
			return uri;
		}

		return uri + ConvertUtil.MapToString(parameters);
	}

}
